package frwa;

import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public final class ActionMap {
    private static ActionMap _instance = null;
    private Map<String, Class<? extends IAction>> actionMap;
    final static Logger Logs = Logger.getLogger(ActionMap.class);

    private ActionMap() throws ConfigException, ConfigNotFoundException, ClassNotFoundException, IncorrectClassException, ActionClassNotFoundException {
        actionMap = new HashMap<>();
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("C://Project/ActionConfig.properties"));
            Enumeration enumeration = properties.keys();
            if (!enumeration.hasMoreElements()) throw new ConfigException();
            while (enumeration.hasMoreElements()) {
                String e = (String) enumeration.nextElement();
                Class<? extends IAction> actionClass;
                try {
                    actionClass = (Class<? extends IAction>) Class.forName(properties.getProperty(e));
                } catch (ClassNotFoundException e1) {
                    throw new ActionClassNotFoundException();
                } catch (ClassCastException exp) {
                    throw new IncorrectClassException();
                }
                actionMap.put(e, actionClass);
            }
        } catch (IOException e) {
            throw new ConfigNotFoundException();
        }
    }

    public static synchronized ActionMap getInstance() throws ConfigException, ConfigNotFoundException, ClassNotFoundException, IncorrectClassException, ActionClassNotFoundException {
        if (_instance == null) {
            _instance = new ActionMap();
        }
        return _instance;
    }

    public IAction getAction(String operationName) throws ActionNotFoundException {
        Logs.info(actionMap.get(operationName));
        try {
            return actionMap.get(operationName).newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new ActionNotFoundException();
        }
    }

}